package com.tange.ai.iot.client.gnssa.binding

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import androidx.appcompat.app.AppCompatActivity
import com.tange.ai.iot.client.gnssa.databinding.ActivityBindingDirectlyBinding
import com.tange.base.toolkit.DateUtil
import com.tange.base.toolkit.Tips
import com.tange.base.toolkit.onClicked
import com.tange.base.ui.design.BasicDialogLoading
import com.tange.feature.binding.query.DeviceBindingDirectly

class BindingDirectlyActivity: AppCompatActivity() {

    private companion object {
        const val REQ_CODE = 8
    }


    private lateinit var binding: ActivityBindingDirectlyBinding

    private var loading: BasicDialogLoading? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityBindingDirectlyBinding.inflate(layoutInflater).apply {
            setContentView(root)
            supportActionBar?.hide()

            scan.onClicked {
                startActivityForResult(Intent(this@BindingDirectlyActivity, BindingQrcodeScanActivity::class.java), REQ_CODE)
            }
        }

        com.tange.ai.iot.client.gnssa.utils.Utils.setStatusBar(this, Color.TRANSPARENT)

        binding.deviceNameEt.setText("摄像头-${DateUtil.getTodayDate()}")

        binding.next.setOnClickListener { bind() }

        binding.next.post {
            Tips.show("可以点击右侧小图标以扫描二维码")
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == REQ_CODE && RESULT_OK == resultCode) {
            val id = data?.getStringExtra("device_id") ?: ""
            binding.deviceIdEt.setText(id)
        }
    }

    private fun bind() {
        val deviceId = binding.deviceIdEt.text.trim().toString()
        if (TextUtils.isEmpty(deviceId)) {
            Tips.show("empty device id")
            return
        }

        val deviceName = binding.deviceNameEt.text.trim().toString()

        if (loading?.isShowing == true) {
            loading?.dismiss()
        }

        loading = BasicDialogLoading(this).apply {
            setMessage("绑定中...")
        }
        loading?.show()

        DeviceBindingDirectly.require(deviceId, deviceName) {
            loading?.dismiss()
            if (it.success) {
                Tips.show("绑定成功！")
                finish()
            } else {
                Tips.show("绑定失败: code = ${it.code} , msg = ${it.message}")
            }
        }
    }

}

